/*
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */
package com.amazonaws.demo;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.amazonaws.demo.sdb.SimpleDB;
import com.twilio.sdk.TwilioRestClient;
import com.twilio.sdk.TwilioRestException;
import com.twilio.sdk.resource.factory.SmsFactory;
import com.twilio.sdk.resource.instance.Account;
import com.twilio.sdk.resource.instance.Sms;
public class newUser extends Activity {
	protected Button register;
	private EditText logInName;
	private EditText password;
	private EditText repeatPassword;
	public static AmazonClientManager clientManager = null;
	public Context context;
	public static final String ACCOUNTSID = "ACa8cd84343d08f6f84fd3ca5b1c532751";
	public static final String AUTHTOKEN = "dd10c126da38021664352140c022b0a6";
	public static final int SEND_MESSAGE = 1;
	private int randomCode;
	private Handler myHandler;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_user);
		context = this;
		register = (Button) findViewById(R.id.register);
		clientManager = new AmazonClientManager();
		logInName = (EditText)findViewById(R.id.loginName);
		password = (EditText)findViewById(R.id.password);
		repeatPassword = (EditText)findViewById(R.id.repeatPassword);
		myHandler = new Handler(){
			public void handleMessage(Message msg){
				// get the data from other thread
				switch(msg.what){
				case SEND_MESSAGE:
					Intent i = new Intent(newUser.this, Verification.class);
					i.putExtra("userPhoneNumber", logInName.getText().toString());
					Log.d("INPUT NUMBER", "" + logInName.getText().toString());
					i.putExtra("userPassword", password.getText().toString());
					startActivity(i);
					break;

				}
			}
		};
		register.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Thread thread = new Thread(new Runnable(){
					public void run(){

						if(!checkUserInput()){
							runOnUiThread(new Runnable(){
								public void run(){
									Toast.makeText(getApplicationContext(), "There are error in your input.", Toast.LENGTH_SHORT).show();
								}
							}
									);
						}else{		
							SharedPreferences settings = getSharedPreferences("preference", 0);


							if(checkSendMsg()){
								sendTextMessage();
							}else{
								runOnUiThread(new Runnable(){
									public void run(){
										SharedPreferences settings = getSharedPreferences("preference", 0);

										Toast.makeText(getApplicationContext(), "Please wait for " + (Math.pow(10, settings.getInt("msgCounter", 0) - 2) - 
												System.currentTimeMillis() / 60000 +  settings.getLong("lastTimeSendMsg", 0)/60000) + " mins to register again.", 
												Toast.LENGTH_SHORT).show();
									}
								});
								

							}
							


							//	Random randomGenerator = new Random();
							//	randomCode = randomGenerator.nextInt(100000);
						}
					}
				});
				thread.start();	
			}
		});

		// Check if the username already exists

	}

	//check to see if the new user input is valid
	private boolean checkUserInput(){
		//check to see if the phone number already exists
		if (SimpleDB.getDomainNames().contains(logInName.getText().toString())){
			return false;
			//check to see if any one of the password field is empty
		}else if(password.getText().toString() == "" || repeatPassword.getText().toString() == ""){
			return false;
			//check to see if the two password fields are the same
		}else if(!password.getText().toString() .equals( repeatPassword.getText().toString())){
			return false;
		}else if(password.getText().toString().length() < 6){
			return false;
		}else{
			return true;	
		}
	}

	public void sendTextMessage(){
		//		AWSCredentials credentials = new BasicAWSCredentials( PropertyLoader.getInstance().getAccessKey(), PropertyLoader.getInstance().getSecretKey() );
		//		Region region = Region.getRegion(Regions.US_EAST_1); 
		//		AmazonSNSClient snsClient = new AmazonSNSClient( credentials );
		//	    snsClient.setRegion(region);
		//		
		//		
		//		
		//		
		//		CreateTopicRequest ctr = new CreateTopicRequest( "eat2gether1" );
		//		CreateTopicResult result = snsClient.createTopic( ctr );	        
		//		SetTopicAttributesRequest tar = new SetTopicAttributesRequest( result.getTopicArn(), "DisplayName", "you earn 3000 dollars" );
		//		snsClient.setTopicAttributes( tar );  
		//	
		//		
		//		//SubscribeRequest sr1 = new SubscribeRequest(result.getTopicArn(), "email", "jingyuan24@gmail.com" );
		//
		//		SubscribeRequest sr1 = new SubscribeRequest(result.getTopicArn(), "sms", "12066608173" );
		//		snsClient.subscribe( sr1 );
		Random randomGenerator = new Random(System.currentTimeMillis());
		randomCode = randomGenerator.nextInt(10000);
		
		SharedPreferences settings = getSharedPreferences("preference", 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putInt("verificationCode", randomCode);
		editor.commit();

		/* Instantiate a new Twilio Rest Client */
		TwilioRestClient client = new TwilioRestClient(ACCOUNTSID, AUTHTOKEN);

		// Get the account and call factory class
		Account acct = client.getAccount();
		SmsFactory smsFactory = acct.getSmsFactory();

		String fromNumber = "425-728-7464";
		Map<String,String> params = new HashMap<String,String>();
		params.put("From", fromNumber);
		params.put("To", "2066608173");
		params.put("Body", "Ahoy from E2gether! your verification number is "+ randomCode);

		try {
			// send an sms a call  
			// ( This makes a POST request to the SMS/Messages resource)
			Sms sms = smsFactory.create(params);
			Message msg = myHandler.obtainMessage(SEND_MESSAGE) ;
    		myHandler.sendMessage(msg);
			System.out.println("Success sending SMS: " + sms.getSid());
		}
		catch (TwilioRestException e) {
			e.printStackTrace();
		}


	}


	public boolean checkSendMsg(){
		SharedPreferences settings = getSharedPreferences("preference", 0);

		if(!settings.contains("lastTimeSendMsg")){		
			SharedPreferences.Editor editor = settings.edit();
				editor.putInt("msgCounter", 0);
				editor.putLong("lastTimeSendMsg", System.currentTimeMillis());
				editor.commit();
		}
		
		if(settings.getInt("msgCounter", 0) < 2){
			SharedPreferences.Editor editor = settings.edit();
			editor.putInt("msgCounter", settings.getInt("msgCounter", 0) + 1);
			editor.putLong("lastTimeSendMsg", System.currentTimeMillis());
			editor.commit();
			return true;
		}else{
			if((System.currentTimeMillis() - settings.getLong("lastTimeSendMsg", 0)) / 60000 < Math.pow(10, settings.getInt("msgCounter", 0) -2)  ){
				return false;
			}else{
				SharedPreferences.Editor editor = settings.edit();
				editor.putInt("msgCounter", settings.getInt("msgCounter", 0) + 1);
				editor.putLong("lastTimeSendMsg", System.currentTimeMillis());
				editor.commit();
				return true;
			}
		}
	}








}
